package com.yonyou.cyxdms.sysAuth.service.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.cyx.framework.service.http.HttpRequestService;
import com.yonyou.cyx.function.bean.dto.http.RestServiceRequestDto;
import com.yonyou.cyx.function.bean.dto.http.RestServiceResponseDto;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.UserAuthConstant;
import com.yonyou.cyxdms.sysAuth.service.dto.authorization.GqwlUserInfo;
import com.yonyou.cyxdms.sysAuth.service.service.UserAuthService;
import com.yonyou.cyxdms.sysAuth.service.service.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: tanjie
 * @Description:
 * @Date: Create in 17:13 2019/7/23
 */

@Service(UserAuthConstant.SERVICE_NAME_USER_AUTH + UserAuthConstant.APP_SOURCE_GQWL)
@Transactional(rollbackFor = Exception.class)
public class GqwlUserAuthServiceImpl implements UserAuthService {

    // 日志对象
    private static final Logger logger = LoggerFactory.getLogger(GqwlUserAuthServiceImpl.class);

    @Autowired
    public UserService userService;

    @Value("${user-auth." + UserAuthConstant.APP_SOURCE_GQWL + ".auth-url}")
    private String gqwlAuthUrl;

    @Autowired
    HttpRequestService service;

    @Override
    public LoginInfoDto getAppUserInfo(String token) {
        logger.debug("访问地址：{},token:{}", gqwlAuthUrl, token);

        Map<String, String> requestHeaderParam = new HashMap<>();
        requestHeaderParam.put("jwt", token);
        // 定义请求对象
        RestServiceRequestDto requestDto = new RestServiceRequestDto();
        requestDto.setUrl(gqwlAuthUrl);
        requestDto.setHeadersParams(requestHeaderParam);

        RestServiceResponseDto responseDto = service.getRequest(requestDto);
        if (responseDto.getResultCode() == RestServiceResponseDto.SUCCESS) {
            try {
                logger.debug("返回data:{}", responseDto.getResponseMsg());
                JSONObject jsonResponse = JSONObject.parseObject(responseDto.getResponseMsg());
                if (jsonResponse == null || jsonResponse.isEmpty() || !jsonResponse.containsKey("resultCode")
                        || jsonResponse.getInteger("resultCode") != 200 || !jsonResponse.containsKey("data")) {
                    throw new ServiceBizException(
                            jsonResponse != null && !jsonResponse.isEmpty() && jsonResponse.containsKey("errMsg")
                                    ? jsonResponse.getString("errMsg")
                                    : "认证接口请求异常");
                }
                JSONObject data = jsonResponse.getJSONObject("data");
                if (data == null || data.isEmpty()) {
                    throw new ServiceBizException("数据错误或此jwt不合法");
                }

//				LoginInfoDto userAccount = iUserPOService.getUserInfoByUserCode(UserAuthConstant.APP_SOURCE_GQWL, data.getString("userAccount"));

                GqwlUserInfo gqwlUserInfo = JSONUtil.jsonToObj(JSONUtil.objectToJson(data), GqwlUserInfo.class);

                LoginInfoDto dto = new LoginInfoDto();
                dto.setAppId(UserAuthConstant.APP_SOURCE_GQWL);
                dto.setOwnerCode(gqwlUserInfo.getDealerCode());
                dto.setDealerName(gqwlUserInfo.getDealerName());
                dto.setUserId(gqwlUserInfo.getUserId());
				dto.setUserName(gqwlUserInfo.getUserName());
				dto.setUserCode(gqwlUserInfo.getUserAccount());
				dto.setEmployeeId(gqwlUserInfo.getEmployeeId());
				dto.setEmployeeNo(gqwlUserInfo.getEmployeeNo());
				dto.setLoginWay(gqwlUserInfo.getLoginWay());
				dto.setEmpId(gqwlUserInfo.getEmpId());
				dto.setOrgId(gqwlUserInfo.getOrgId());

                return dto;
            } catch (Exception e) {
                throw new ServiceBizException("数据错误或此jwt不合法");
            }
        } else {
            throw new ServiceBizException("此jwt 不合法");
        }
    }
}
